package com.seeyon.apps.brwh.kit;


import com.alibaba.fastjson.JSONObject;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.content.mainbody.CtpContentAllBean;
import com.seeyon.ctp.common.content.mainbody.MainbodyService;
import com.seeyon.ctp.common.content.mainbody.MainbodyStatus;
import com.seeyon.ctp.common.content.mainbody.MainbodyType;
import com.seeyon.ctp.common.ctpenum.dao.cache.CtpEnumItemCache;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.UUIDLong;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

public class FormCap4Kit {
    private static Log log = LogFactory.getLog(FormCap4Kit.class);
    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private static CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager) AppContext.getBean("cap4FormDataManager");

    private static CtpEnumItemCache ctpEnumItemCache = (CtpEnumItemCache)AppContext.getBean("ctpEnumItemCache");

    private static TemplateManager templateManager = (TemplateManager) AppContext.getBean("templateManager");
    public static Object getFieldValue(FormDataBean bean, String disPlay) {
        if(bean == null) {
            return null;
        }
        FormTableBean table = bean.getFormTable();
        if(table == null) {
            return null;
        }
        FormFieldBean field = table.getFieldBeanByDisplay(disPlay);
        if(field == null) {
            return null;
        }
        return bean.getFieldValue(field.getName());
    }


    /**
     * 根据明细表显示名称获取明细表数据
     * @param master
     * @param disPlay
     * @return
     */
    public static List<FormDataSubBean> getSubBeansByDisplay(FormDataMasterBean master, String disPlay) {
        Map<String, List<FormDataSubBean>> subs = master.getSubTables();
        if(null != subs && subs.size() > 0) {
            for(String key : subs.keySet()) {
                if(disPlay.equals(subs.get(key).get(0).getFormTable().getDisplay())) {
                    return subs.get(key);
                }
            }
        }
        return null;
    }


    /**
     * 根据明细表显示名称，通过FormBean获取明细表信息
     * @param formBean
     * @param disPlay
     * @return
     */
    public static FormTableBean getSubFormTableBeanByDisplay(FormBean formBean,String disPlay){
        List<FormTableBean> collect = formBean.getSubTableBean().stream().filter(f -> f.getDisplay().equals(disPlay)).collect(Collectors.toList());
        if(!collect.isEmpty()){
            FormTableBean formTableBean = collect.get(0);
            return formTableBean;
        }else {
            return null;
        }
    }


    /**
     * Description:
     * <pre>获取从表字段</pre>
     * @param sub
     * @param disPlay
     * @return
     */
    public static Object getSubFieldValue(FormDataSubBean sub, String disPlay) {
        return getFieldValue(sub, disPlay);
    }


    /**
     * 获取Cap4  FormFieldBean
     * @param formBean
     * @param disPlay
     * @return
     */
    public static FormFieldBean getFormFieldBean(FormBean formBean,String disPlay){
        FormFieldBean fieldBeanByDisplay = formBean.getFieldBeanByDisplay(disPlay);
        return fieldBeanByDisplay;
    }


    /**
     * 判断表中是否存在数据
     * @param fieldNameList
     * @param tempCode
     * @return
     */
    public static String isTableData(List<HashMap<String,Object>> fieldNameList,String tempCode,String tableName){
        FormBean formBean = null;
        try {
            formBean = cap4FormManager.getFormByFormCode(tempCode);
        } catch (BusinessException e) {
            log.info("根据模板编号获取表单数据异常_模板编号为："+tempCode+"——："+e);
            return null;
        }
        if(tableName == null){
            FormTableBean masterTableBean = formBean.getMasterTableBean();
            tableName = masterTableBean.getTableName();
        }
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ID FROM "+tableName+" WHERE 1=1 ");
        for (HashMap<String,Object> s : fieldNameList) {
            String name = s.get("name").toString();
            String value1 = s.get("value").toString();
            //获取字段信息
            FormFieldBean sqdh = formBean.getFieldBeanByDisplay(name);
            sql.append(" and "+ sqdh.getName() +" = '"+value1+"'");
        }
        List<Map<String, Object>> maps = null;
        try {
            maps = DBKit.excuteSQL(sql.toString(), null);
        } catch (Exception e) {
            log.info("获取表单数据异常——sql："+sql.toString());
            return null;
        }
        if(maps.isEmpty()){
            return null;
        }else{
            String id = maps.get(0).get("id").toString();
            return id;
        }
    }


    /**
     * 删除表单数据
     * @return
     */
    public static Boolean deleteTableData(String tempCode,String masterId){
        FormBean formBean = null;
        try {
            formBean = cap4FormManager.getFormByFormCode(tempCode);
        } catch (BusinessException e) {
            log.info("根据模板编号获取表单数据异常_模板编号为："+tempCode+"——："+e);
            return null;
        }
        FormTableBean masterTableBean = formBean.getMasterTableBean();
        String sql = "DELETE FROM "+masterTableBean.getTableName() + " WHERE ID = '" + masterId +"'";
        try {
            DBKit.updateOrDelData(sql);
        } catch (BusinessException e) {
            log.info("根据masterId 删除表单数据异常——sql语句："+sql+",异常信息："+e);
            return false;
        }
        return true;
    }


    /**
     * 根据表单备注字段获取数据
     * @author chy
     * descList  需要获取的备注名称集合
     */
    public static List<HashMap<String,HashMap<String,Object>>> getFormFieldByDesc(List<String> descList,String tempCode){
        List<HashMap<String, HashMap<String,Object>>> resultDataMapList = new ArrayList<>();
        FormBean formBean = null;
        try {
            formBean = cap4FormManager.getFormByFormCode(tempCode);
        } catch (BusinessException e) {
            log.info("根据模板编号获取表单数据异常_模板编号为："+tempCode+"——："+e);
        }
        if(formBean != null){
            List<FormTableBean> tableList = formBean.getTableList();
            for (FormTableBean formTableBean : tableList) {
                HashMap<String, HashMap<String,Object>> tableMap = new HashMap<>();
                String tableName = formTableBean.getTableName();
                Map<String, FormFieldBean> fieldMap4Name = formTableBean.getFieldMap4Name();
                HashMap<String, Object> fieldMap = new HashMap<>();
                for (String s : fieldMap4Name.keySet()) {
                    String desc = fieldMap4Name.get(s).getDesc();
                    if(desc != null && !desc.equals("") && descList.contains(desc)){
                        fieldMap.put(desc,s);
                    }
                }
                tableMap.put(tableName,fieldMap);
                resultDataMapList.add(tableMap);
            }
        }
        return resultDataMapList;
    }

    /**
     * 根据表单备注字段获取数据
     * @author chy
     * descList  需要获取的备注名称集合
     */
    public static List<HashMap<String, Object>> getFormFieldByDescMsterBean(List<String> descList,FormDataMasterBean formDataMasterBean){
        List<HashMap<String, Object>> resultDataMapList = new ArrayList<>();
        if(formDataMasterBean != null){
            //主表
            FormTableBean formTable = formDataMasterBean.getFormTable();
            HashMap<String, Object> tableMap = new HashMap<>();
            HashMap<String, HashMap<String,Object>> fieldMap = new HashMap<>();
            Map<String, FormFieldBean> fieldMap4Name1 = formTable.getFieldMap4Name();
            for (String s : fieldMap4Name1.keySet()) {
                FormFieldBean formFieldBean = fieldMap4Name1.get(s);
                String display = formFieldBean.getDisplay();
                String desc = fieldMap4Name1.get(s).getDesc();
                if(descList.contains(desc)){
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("fieldName",s);
                    map.put("fieldDisplay",display);
                    map.put("desc",desc);
                    fieldMap.put(desc,map);
                }
            }
            tableMap.put("tableName",formTable.getTableName());
            tableMap.put("tableType","1");
            tableMap.put("tableFieldData",fieldMap);
            resultDataMapList.add(tableMap);
            //明细表
            Map<String, List<FormDataSubBean>> subTables = formDataMasterBean.getSubTables();
            for (String s : subTables.keySet()) {
                HashMap<String, Object> subDataMap = new HashMap<>();
                HashMap<String, HashMap<String,Object>> subFieldMap = new HashMap<>();
                FormDataSubBean formDataSubBean1 = subTables.get(s).get(0);
                Map<String, FormFieldBean> fieldMap4Name2 = formDataSubBean1.getFormTable().getFieldMap4Name();
                for (String s1 : fieldMap4Name2.keySet()) {
                    FormFieldBean formFieldBean = fieldMap4Name2.get(s1);
                    String display = formFieldBean.getDisplay();
                    String desc = fieldMap4Name2.get(s1).getDesc();
                    if(descList.contains(desc)){
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("fieldName",s1);
                        map.put("fieldDisplay",display);
                        map.put("desc",desc);
                        subFieldMap.put(desc,map);
                    }
                }
                subDataMap.put("tableName",s);
                subDataMap.put("tableType","2");
                subDataMap.put("tableFieldData",subFieldMap);
                resultDataMapList.add(subDataMap);
            }
        }
        return resultDataMapList;
    }

    /**
     * 保存表单数据
     * @param member           操作人员
     * @param tempCode         表单模板编号
     * @param mapDataList      需要保存的数据，参数关键组装如下：
     *  //封装主表数据
     *  HashMap<String,Object> masterData = new HashMap<String, Object>()
     *  masterData("控件显示名称","控件值")
     *
     *  //封装添加明细表数据
     *  List<HashMap<String, Object>> mxDataList = new ArrayList<>();
     *  HashMap<String, Object> subMap = new HashMap<>();
     *  subMap.put("字段显示名称","字段的值")
     *  mxDataList.add(subMap)
     *
     *  //封装明细表数据
     *  HashMap<String, List<HashMap<String, Object>>> mxDataMap = new HashMap<>();
     *  mxDataMap.("明细表显示名称",mxDataList)
     *
     *  //封装需要保存数据
     *  HashMap<String, Object> saveDataMap = new HashMap<>();
     *  //添加主表数据
     *  saveDataMap.put("masterData",masterData);
     *  //明细表数据    如果不需要添加明细表，可以为null
     *  saveDataMap.put("mxData",mxDataMap);
     *
     *  //添加需要组装的数据
     *  List<HashMap<String, Object>> mapDataList = new ArrayList<>();
     *  mapDataList.add(saveDataMap);
     *
     * @return
     */
    public static Boolean saveCAP4FormData(V3xOrgMember member, String tempCode, List<HashMap<String, Object>> mapDataList) {
        Boolean isSave = false;
        // 需要保存的底表数据
        List<FormDataMasterBean> masterdatas = new ArrayList<>();
        FormBean bean;
        try {
            bean = cap4FormManager.getFormByFormCode(tempCode);
        } catch (BusinessException e) {
            log.info("根据模板编号获取表单数据异，模板编号为：" + tempCode);
            return isSave;
        }
        //主表
        FormTableBean formTableBean = bean.getMasterTableBean();
        //明细表
        List<FormTableBean> subTableBeanList = bean.getSubTableBean();

        //获取表中所有字段信息
        List<FormFieldBean> fieldList = formTableBean.getFields();

        Map<String, FormFieldBean> fields = new HashMap<>();
        // 所有字段的集合
        for (FormFieldBean field : fieldList) {
            fields.put(field.getDisplay(), field);
        }

        //循环获取需要保存的数据
        for (HashMap<String, Object> mapData : mapDataList) {
            //获取主表数据
            HashMap<String, Object> masterData = (HashMap<String, Object>) mapData.get("masterData");
            //添加主表信息
            FormDataMasterBean dataMasterBean = FormDataMasterBean.newInstance(bean);
            for (String s : masterData.keySet()) {
                Set<String> strings = fields.keySet();
                if (strings.contains(s)) {
                    FormFieldBean formFieldBean = fields.get(s);
                    dataMasterBean.addFieldValue(formFieldBean.getName(), masterData.get(s));
                }
            }

            //获取明细表数据
            Object mxDataObject = mapData.get("mxData");
            log.info("保存档案表数据中明细表数据："+ JSONObject.toJSONString(mxDataObject));
            if (mxDataObject != null) {
                HashMap<String, List<HashMap<String, Object>>> mxData = (HashMap<String, List<HashMap<String, Object>>>) mxDataObject;
                for (String s : mxData.keySet()) {
                    for (FormTableBean tableBean : subTableBeanList) {
                        String subTableName = tableBean.getTableName();
                        String display = tableBean.getDisplay();
                        log.info("获取到的明细表名称："+subTableName+"___显示名称："+display);
                        if (display.equals(s)) {
                            //添加明细表数据
                            List<HashMap<String, Object>> hashMaps = mxData.get(s);
                            List<FormDataSubBean> subDatas = new ArrayList<>();
                            for (HashMap<String, Object> map : hashMaps) {
                                HashMap<String, Object> subData = new HashMap<>();
                                for (String s1 : map.keySet()) {
                                    subData.put(tableBean.getFieldBeanByDisplay(s1).getName(), map.get(s1));
                                }
                                FormDataSubBean formDataSubBean = new FormDataSubBean(subData, tableBean, dataMasterBean, false);
                                formDataSubBean.setIdIfNew();
                                formDataSubBean.setFormmainId(dataMasterBean.getId());
                                subDatas.add(formDataSubBean);
                            }
                            dataMasterBean.setSubData(tableBean.getTableName(), subDatas);
                        }
                    }
                }
            }
            try {
                saveContent(bean, dataMasterBean.getId(), member.getId());
            } catch (BusinessException e) {
                log.info("添加正文失败：" + e);
            }
            masterdatas.add(dataMasterBean);
        }
        try {
            //添加表单数据
            cap4FormDataManager.insertOrUpdateMasterData(masterdatas, false);
            isSave = true;
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return isSave;
    }

    /**
     * 修改主表表单数据
     * @param masterId   修改数据的Id
     * @param tempCode   模板编号
     * @param map        需要修改的数据{key:字段显示名称,value:值}
     */
    public static void updateCAP4FormData(Long masterId,String tempCode,HashMap<String ,Object> map){
        log.info("开始修改主表字段----------");
        FormBean formBean = null;
        try {
            formBean = cap4FormManager.getFormByFormCode(tempCode);
        } catch (BusinessException e) {
            log.info("根据模板编号获取表单数据异常_模板编号为："+tempCode+"——："+e);
            return;
        }
        FormTableBean masterTableBean = formBean.getMasterTableBean();
        String tableName = masterTableBean.getTableName();
        HashMap<String ,Object> upMap = new HashMap<>();

        for (String s : map.keySet()) {
            //获取字段信息
            FormFieldBean sqdh = formBean.getFieldBeanByDisplay(s);
            if(sqdh == null){
                continue;
            }
            upMap.put(sqdh.getName(),map.get(s));
        }

        try {
            cap4FormDataManager.updateData(masterId,tableName,upMap);
        } catch (BusinessException e) {
            log.info("修改表单数据失败BusinessException：",e);
        } catch (SQLException e) {
            log.info("修改表单数据失败SQLException：",e);
        }
    }


    /**
     * 获取报表地址
     * @param title
     * @return
     */
    public static String getBbAddres(String title){
        String url = "/seeyon/report4Result.do?method=showResult&designId=";
        String BbId = "";
        String BBSql = "select id from report_design where title = '"+title+"'";
        List<Map<String, Object>> BBMapList = new ArrayList<>();
        try {
            BBMapList = DBKit.excuteSQL(BBSql, null);
        } catch (Exception e) {
            log.error("看板获取报表数据异常，sql："+BBSql+"————异常结果：",e);
        }
        if(!BBMapList.isEmpty()){
            Map<String, Object> stringObjectMap = BBMapList.get(0);
            BbId = stringObjectMap.get("id").toString();
        }else{
            BbId = "-1";
        }
        url+=BbId;
        return url;
    }


    /**
     * 获取跳转档案表页面地址
     * @param tempCode   模板编码
     * @param masterId   主表数据Id
     * @return
     */
    public static String getDabAddres(String tempCode,String masterId){
        CtpTemplate ctpTemplate = templateManager.getTempleteByTemplateNumber(tempCode);
        String url = "/seeyon/cap4/businessTemplateController.do?method=formContent&type=browse&moduleId="+masterId+"&formTemplateId="+ctpTemplate.getId()+"&moduleType=42";
        return url;
    }


    /**
     * 修改明细表数据
     * @param masterId
     * @param tempCode
     */
    private static String upSubData(Long masterId,String tempCode,List<HashMap<String ,Object>> mapList,String tableName,ArrayList<String> conditionMap){
        FormBean formBean = null;
        try {
            formBean = cap4FormManager.getFormByFormCode(tempCode);
        } catch (BusinessException e) {
            log.info("根据模板编号获取表单数据异常_模板编号为："+tempCode+"——："+e);
            return "";
        }
        FormDataMasterBean formDataMasterBean = null;
        try {
            formDataMasterBean = cap4FormManager.getDataMasterBeanById(masterId, formBean, null);
        } catch (Exception e) {
            log.info("获取masterBen有误："+masterId);
        }
        //获取明细表对象
        FormTableBean subTableBean = null;
        for (FormTableBean formTableBean : formBean.getSubTableBean()) {
            if(formTableBean.getTableName().equals(tableName)){
                subTableBean = formTableBean;
            }
        }
        List<FormDataSubBean> addSubDataList = new ArrayList<>();
        List<FormDataSubBean> subDataList = formDataMasterBean.getSubData(tableName);
        //去掉默认的第一行空白数据
        if(subDataList.size()==1){
            FormDataSubBean formDataSubBean = subDataList.get(0);
            Boolean isTrue = false;
            for (String s : conditionMap) {
                FormFieldBean fieldBeanByDisplay = formBean.getFieldBeanByDisplay(s);
                if(fieldBeanByDisplay == null){
                    continue;
                }
                Object s1 = formDataSubBean.getFieldValue(fieldBeanByDisplay.getName());
                if(s1 == null || s1.toString().equals("")){
                    isTrue = true;
                }else{
                    isTrue = false;
                }
            }
            if(isTrue){
                subDataList.clear();
            }
        }
        for (HashMap<String, Object> dataMap : mapList) {
            boolean isCz = false;
            for (FormDataSubBean formDataSubBean : subDataList) {
                //判断这条数据是否存在明细表中
                for (String s : conditionMap) {
                    FormFieldBean sb = formBean.getFieldBeanByDisplay(s);
                    if(sb == null){
                        continue;
                    }
                    String s1 = formDataSubBean.getFieldValue(sb.getName()).toString();
                    String s2 = dataMap.get(s).toString();
                    if(s1.equals(s2)){
                        isCz = true;
                    }else{
                        isCz = false;
                    }
                }
                if(isCz){
                    //修改数据
                    for (String s : dataMap.keySet()) {
                        FormFieldBean sb = formBean.getFieldBeanByDisplay(s);
                        if(sb == null){
                            continue;
                        }
                        formDataSubBean.addFieldValue(sb.getName(),dataMap.get(s));
                    }
                    break;
                }
            }
//            if(!isCz){
//                String err = "该条明细数据在OA底表明细行中不存在，查询条件为：";
//                for (String s : conditionMap) {
//                    err += s + "="+dataMap.get(s)+"，";
//                }
//                return err;
//            }
            if(!isCz){
                //添加数据
                Map<String,Object> subData = new HashMap<>();
                for (String s : dataMap.keySet()) {
                    FormFieldBean sb = formBean.getFieldBeanByDisplay(s);
                    if(sb == null ){
                        continue;
                    }
                    subData.put(sb.getName(),dataMap.get(s));
                }
                FormDataSubBean formDataSubBean1 = new FormDataSubBean(subData,subTableBean,formDataMasterBean,false);
                addSubDataList.add(formDataSubBean1);
            }
        }
        subDataList.addAll(addSubDataList);
        formDataMasterBean.setSubData(tableName,subDataList);
        List<FormDataMasterBean> masterdatas = new ArrayList<>();
        masterdatas.add(formDataMasterBean);
        try {
            cap4FormDataManager.insertOrUpdateMasterData(masterdatas, false);
            log.info("添加明细表成功："+masterId+"-表名称："+tableName);
        } catch (Exception e) {
            log.info("添加明细表或修改明细表异常："+e);
        }
        return "";
    }



    /**
     * 保存表单正文信息
     * @param bean
     * @param moduleId
     * @param memberId
     * @return
     */
    private static void saveContent(FormBean bean, Long moduleId, Long memberId) throws BusinessException {
        CtpContentAll ctpContentAll = null;
        CtpContentAllBean ctpContentAllBean=null;
        FormAuthViewBean formAuthViewBean = bean.getNewFormAuthViewBeans().get(0);
        String rightid = String.valueOf(formAuthViewBean.getId());
        log.info("saveMasterAndSubForm finish masterId " + moduleId);
        //正文内容保存
        ctpContentAll = saveContentAllForForm(null, moduleId, memberId, bean,rightid);
        MainbodyService mainBodyService = MainbodyService.getInstance();
        mainBodyService.saveOrUpdateContentAll(ctpContentAll);
    }


    /**
     * 封装获取ContentAll数据
     * @param ctpContentAll
     * @param masterId
     * @param userid
     * @param formBean
     * @param rightId
     * @return
     * @throws BusinessException
     */
    private static CtpContentAll saveContentAllForForm(CtpContentAll ctpContentAll, long masterId, long userid,
                                                FormBean formBean,String rightId) throws BusinessException {
        Timestamp timestamp = com.seeyon.ctp.util.DateUtil.currentTimestamp();
        if (ctpContentAll != null) {
            ctpContentAll.setModifyId(userid);
            ctpContentAll.setModifyDate(timestamp);
            return ctpContentAll;
        }
        CtpContentAllBean content = new CtpContentAllBean();

        FormBindBean bindBean = formBean.getBind();
        if (bindBean != null) {
            content.setModuleTemplateId(bindBean.getId());
            Map<String, FormBindAuthBean> bindAuth = bindBean.getUnFlowTemplateMap();
            if (CollectionUtils.isEmpty(bindAuth.values())) {
                throw new BusinessException("无应用绑定");
            }
            for (FormBindAuthBean authBean : bindAuth.values()) {
                content.setTitle(authBean.getName());
            }
        }
        content.setModuleType(getModuleType(formBean));
        content.setCreateId(userid);
        content.setCreateDate(timestamp);
        content.setSort(0);
        content.setId(UUIDLong.longUUID());
        content.setStatus(MainbodyStatus.STATUS_POST_SAVE);
        content.setContentType(Integer.valueOf(MainbodyType.FORM.getKey()));
        content.setContentTemplateId(formBean.getId());
        content.setContentDataId(masterId);
        content.setModuleId(masterId);
        content.setModifyDate(timestamp);
        content.setModifyId(userid);
        content.setRightId(rightId);

        return content.toContentAll();
    }


    private static int getModuleType(FormBean formBean) throws BusinessException {
        com.seeyon.cap4.form.util.Enums.FormType formType = com.seeyon.cap4.form.util.Enums.FormType.getEnumByKey(formBean.getFormType());
        if(formType != null){
            return formType.getModuleType().getKey();
        }else{
            log.warn("无效表类型");
            throw new BusinessException("内容保存失败");
        }
    }


    /**
     * 根据枚举编码获取枚举信息
     * @param itemCode
     * @return
     */
    public static List<CtpEnumItem> getEnumByNameList(String itemCode){
        Iterator var4 = ctpEnumItemCache.findAll().iterator();
        List<CtpEnumItem> items = new ArrayList<CtpEnumItem>();
        while(var4.hasNext()) {
            CtpEnumItem entry = (CtpEnumItem)var4.next();
            if (itemCode.equals(entry.getEnumItemCode())) {
                items.add(entry);
            }
        }
        return items;
    }

    /**
     * 根据枚举项编码查获取枚举项
     * @param itmeCode
     * @return
     * @throws BusinessException
     */
    public static CtpEnumItem getEnumByCode(String itmeCode) throws BusinessException {
        // 检查输入的枚举项代码是否为空或空白字符串
        if (Strings.isBlank(itmeCode)) {
            return null;
        } else {
            // 初始化一个账户ID变量，用于后续比较
            Long accountId = null;
            // 遍历枚举项缓存中的所有条目
            Iterator var4 = ctpEnumItemCache.findAll().iterator();

            while (var4.hasNext()) {
                CtpEnumItem entry = (CtpEnumItem) var4.next();
                // 如果accountId为null，且当前枚举项的代码与输入代码匹配，则返回该枚举项
                if (accountId == null) {
                    if (itmeCode.equals(entry.getEnumItemCode())) {
                        return entry;
                    }
                } else if (itmeCode.equals(entry.getEnumItemCode())) {
                    // 如果accountId不为null，且当前枚举项的代码与输入代码匹配，则返回该枚举项
                    return entry;
                }
            }

            // 如果遍历完成后仍未找到匹配的枚举项，则返回null
            return null;
        }
    }
}
